var config = parent.parent.CONFIG,system=parent.parent.SYSTEM;
if(!config){
	config = parent.parent.parent.CONFIG;
	system = parent.parent.parent.SYSTEM;
}
var api = frameElement.api, W = api.opener;
var callback = api.data.callback,oper = api.data.oper;

var Utils = {
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择店铺',
			content : 'url:'+config.BASEPATH+'base/shop/to_list_sub_dialog',
			data : {multiselect:true},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					var codes = [];
					var names = [];
					for(var i=0;i<selected.length;i++){
						codes.push(selected[i].sp_code);
						names.push(selected[i].sp_name);
					}
					$("#sc_shop_code").val(codes.join(","));
					$("#sc_shop_name").val(names.join(","));
				}
			},
			cancel:true
		});
	},
	clickScType:function(sc_type){
		$("#sc_type").val(sc_type);
		if(sc_type == '0'){//全场
			$("#detailDiv").css("display","none");
			$(".border").css("border-bottom","#ddd solid 1px");
		}else{
			$("#detailDiv").css("display","");
			$(".border").css("border-bottom","0");
		}
		THISPAGE.initGrid(sc_type);
		THISPAGE.initEvent();
	},
	doQueryBrand : function(){
		commonDia = $.dialog({
			title : '选择品牌',
			content : 'url:'+config.BASEPATH+'base/brand/to_list_dialog',
			data : {multiselect:true},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				var datas = [];
				for(var i=0;i<selected.length;i++){
					var node = {};
					node.Code = selected[i].bd_code;
					node.Name = selected[i].bd_name;
					datas.push(node);
				}
				Utils.callback(datas)
			},
			cancel:true
		});
	},
	doQueryType : function(){
		commonDia = $.dialog({
			title : '选择类别',
			content : 'url:'+config.BASEPATH+'base/type/to_tree_dialog',
			data : {multiselect:true},
			width : 280,
		   	height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					Public.tips({type: 2, content : '请选择商品类别!'});
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				var datas = [];
				for(var i=0;i<selected.length;i++){
					var node = {};
					node.Code = selected[i].tp_code;
					node.Name = selected[i].tp_name;
					datas.push(node);
				}
				Utils.callback(datas)
			},
			cancel:true
		});
	},
	doQueryProduct : function(){
		commonDia = $.dialog({
			title : '选择商品',
			content : 'url:'+config.BASEPATH+'base/product/to_list_dialog',
			data : {multiselect:true},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				var datas = [];
				for(var i=0;i<selected.length;i++){
					var node = {};
					node.Code = selected[i].pd_code;
					node.Name = selected[i].pd_name;
					datas.push(node);
				}
				Utils.callback(datas)
			},
			cancel:true
		});
	},
	callback:function(datas){
		if(datas){
			var ids = $("#grid").jqGrid('getDataIDs');
			var index = THISPAGE.maxId+1;
			var exist = false;
			for(var i=0;i<datas.length;i++){
				var data = datas[i];
				exist = false;
				for(var j=0;j < ids.length;j++){
					var rowData = $('#grid').jqGrid('getRowData',ids[j]);
					if(rowData.Code == data.Code){
						exist = true;
					}
				}
				if(!exist){
					THISPAGE.addGridData(index, data);
					THISPAGE.maxId = index;
					index++;
				}
			}
		}
	}
};

var handle = {
	save:function(){
		var sc_shop_code = $("#sc_shop_code").val();
		var sc_name = $("#sc_name").val();
		var sc_amount = $("#sc_amount").val();
		var sc_minus_money = $("#sc_minus_money").val();
		var sc_full_money = $("#sc_full_money").val();
		var sc_type = $("#sc_type").val();
		if(sc_shop_code == null || sc_shop_code == ""){
			Public.tips({type: 2, content : '请选择 活动门店！'});
			return;
		}
		if(sc_name == null || sc_name ==""){
			Public.tips({type: 2, content : '请输入优惠券方案名称！'});
			return;
		}
		if(sc_amount=='' || isNaN(sc_amount) || parseInt(sc_amount) <= 0){
			Public.tips({type: 2, content : '请输入发放数量！'});
			return;
		}
		if(sc_minus_money=='' || isNaN(sc_minus_money) || parseInt(sc_minus_money) <= 0 ){
			Public.tips({type: 2, content : '请输入面值多少元！'});
			return;
		}
		if(sc_full_money=='' || isNaN(sc_full_money) || parseInt(sc_full_money) <= 0){
			Public.tips({type: 2, content : '请输入使用条件，满多少元！'});
			return;
		}
		if(sc_type == ''){
			Public.tips({type: 2, content : '请选择优惠券范围！'});
			return;
		}
		var params = {};
		params.sc_shop_code = sc_shop_code;
		params.sc_name = Public.encodeURI(sc_name); 
		params.sc_minus_money = sc_minus_money;
		params.sc_full_money = sc_full_money;
		params.sc_amount = sc_amount;
		params.sc_type = sc_type;
		params.sc_begindate = $("#sc_begindate").val();
		params.sc_enddate = $("#sc_enddate").val();
		params.sc_remark = Public.encodeURI($("#sc_remark").val());
		var sc_show_sysinfo = THISPAGE.$_show_sysinfo.chkVal().join() ? true : false;
		if(sc_show_sysinfo){
			params.sc_show_sysinfo = '1';
		}else{
			params.sc_show_sysinfo = '0';
		}
		var sc_show_chat = THISPAGE.$_show_chat.chkVal().join() ? true : false;
		if(sc_show_chat){
			params.sc_show_chat = '1';
		}else{
			params.sc_show_chat = '0';
		}
		if(sc_type != '0'){
			var ids = $("#grid").jqGrid('getDataIDs');
			var codes = '';
			for(var i = 0;i < ids.length; i++){
				var rowData = $('#grid').jqGrid('getRowData',ids[i]);
				if(rowData.Code != ''){
					codes += rowData.Code+',';
				}
			}
			if(codes.length == 0){
				if(sc_type == '1'){
					Public.tips({type: 2, content : '请选择类别！'});
				}else if(sc_type == '2'){
					Public.tips({type: 2, content : '请选择品牌！'});
				}else if(sc_type == '3'){
					Public.tips({type: 2, content : '请选择商品！'});
				}
				return;
			}else{
				codes = codes.substring(0, codes.length-1);
			}
			params.codes = codes;
		}
		$("#btn-save").attr("disabled",true);
		$.ajax({
			type:"POST",
			url:config.BASEPATH+"sell/coupon/save",
			data:params,
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : data.message});
					W.isRefresh = true;
					setTimeout("api.close()",500);
				}else{
					Public.tips({type: 1, content : data.message});
				}
				$("#btn-save").attr("disabled",false);
			}
		});
	},
	ifNumber:function(obj){
 	  	var number = obj.value;
 		if(number == ""){
 			Public.tips({type: 2, content :"请输入买满数量！"});
 			return false;
 		}
 		if(isNaN(number)){
 			Public.tips({type: 2, content :"买满数量只能输入数字！"});
 			obj.value="";
 			return false;
 		}
 		return true;
 	},
 	ifMoney:function(obj){
 	 	var money = obj.value; 
 		if(money == ""){
 			Public.tips({type: 2, content :"请输入金额！"});
 			return false;
 		}
 		if(isNaN(money)){
 			Public.tips({type: 2, content :"金额只能输入数字！"});
 			obj.value="";
 			return false;
 		}
 		return true;
 	},
	operFmatter :function(val, opt, row){
		var html_con = '<div class="operating" style="text-align:center" data-id="' +opt.rowId+ '">';
		html_con += '<span class="iconfont i-hand ui-icon-plus" title="增加">&#xe639;</span>&nbsp;';
		html_con += '<span class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</span>';
		html_con += '</div>';
		return html_con;
	}
};

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid('0');
		this.initEvent();
	},
	initDom:function(){
		this.maxId = 0;
		this.hadEmptyData = false;
		this.$_show_sysinfo = $("#show_sysinfo").cssCheckbox();
		this.$_show_chat = $("#show_chat").cssCheckbox();
	},
	addEmptyData:function(){
    	var emptyData = {};
    	$("#grid").addRowData(0, emptyData);
    },
    addGridData:function(id,gridData){
    	$("#grid").addRowData(id, gridData,'first');
    },
    initGrid:function(sc_type){
		if(sc_type == '0'){
			return;
		}
		var type = '';
		if(sc_type == '1'){
			type='类别';
		}else if(sc_type == '2'){
			type='品牌';
		}else if(sc_type == '3'){
			type='商品';
		}
		var colModel = [
		    {label:'操作',name:'operate', width: 60, fixed:true, formatter: handle.operFmatter, sortable:false},
	    	{label:type+'编号',name: 'Code', index: '',width: 150, fixed:true, align: 'left'},
	    	{label:type+'名称',name: 'Name', index: '', width: 200, fixed:true ,title: true, align: 'left'}
	    ];
		$('#grid').GridUnload();
		this.hadEmptyData = false;
		$('#grid').jqGrid({
			url:'',
			loadonce:true, //只从后台加载一次数据，datatype被修改为local,如果弹出框想要查询则再开启为json
			datatype: 'local',
			autowidth: true,
			//width:960,
			//height: 220,
			autoheight: true,
			altRows:true,
			gridview: true,
			onselectrow: false,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			multiselect:false,//多选
			viewrecords: true,
			cmTemplate: {sortable:true,title:false},
			page: 1, //只有一页
			pgbuttons:false,
			pgtext:false,
			rowNum:100,//每页条数
			shrinkToFit:false,//表格是否自动填充
			scroll: 1,//是否滚动
			jsonReader: {
				root: 'data.rows', 
				total: "data.total",
				page: "data.page",
				records: "data.records",
				repeatitems : false,
				id: 'id'  //图标ID
			},
			loadComplete: function(data){
				if(!THISPAGE.hadEmptyData){
					THISPAGE.addEmptyData();
					THISPAGE.hadEmptyData = true;
				}
				Public.resizeSpecifyGrid("grid", 110, 32);
			},
			loadError: function(xhr, status, error){		
				Public.tips({type: 1, content : '操作失败了哦，请检查您的网络链接！'});
			},
			ondblClickRow:function(rowid,iRow,iCol,e){
			},
			onCellSelect:function(rowid,iRow,iCol,e){
				
			}
	    });
	},
	initEvent:function(){
		$('#btn-save').on('click', function(e){
			e.preventDefault();
			handle.save();
		});
		$("#btn_close").click(function(){
			W.isRefresh = false;
			api.close();
		});
		//增加
        $('#grid').on('click', '.operating .ui-icon-plus', function (e) {
            e.preventDefault();
            var sc_type = $("#sc_type").val();
            if(sc_type == '1'){
            	Utils.doQueryType();
            }else if(sc_type == '2'){
            	Utils.doQueryBrand();
            }else if(sc_type == '3'){
            	Utils.doQueryProduct();
            }
        });
      //删除
        $('#grid').on('click', '.operating .ui-icon-trash', function (e) {
            e.preventDefault();
            var id = $(this).parent().data('id');
            if(id!=0){
            	$.dialog.confirm('数据删除后将不能恢复，请确认是否删除？',function(){
            		$('#grid').jqGrid('delRowData', id);
            	});
            }
        });
        $(window).resize(function(){
			Public.resizeSpecifyGrid("grid",110,32);
		});
	}
};
THISPAGE.init();